package com.simple.base.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.simple.util.ErrorMessageUtil;
import com.simple.util.ErrorsUtil;
import com.simple.util.common.Constants;
import com.simple.util.common.LocaleUtil;
import com.simple.util.object.JFValidationBean;

public class WebErrorMessageInterceptor extends HandlerInterceptorAdapter {
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler) throws Exception {
		final String siteLanguage = LocaleUtil.getLocaleFromRquest(request);
		request.setAttribute(Constants.SITE_LANGUAGE, siteLanguage);
		return true;
	}
	

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
			throws Exception {
		final List<JFValidationBean> errorList = ErrorMessageUtil.getErrorList();
		
		if(!errorList.isEmpty()){
        	final String errorMessage = ErrorsUtil.getJavascriptErrorMessage((String) request.getAttribute(Constants.SITE_LANGUAGE), errorList);
            request.setAttribute("errorMessage", errorMessage);
        }
	}
	
	@Override
	public void afterCompletion(
			HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		ErrorMessageUtil.remove();
	}
	
}
